//app.js
const env = require('./config.js').env;
const assets = require('./config.js').assets;
const assetsByEnv = '/resources';
const userService = require('./services/userService');
const messageService = require('./services/messageService');
const mta = require('./utils/mta_analysis');
const logger = require('./utils/logger');
App({
  onLaunch: function () {
    mta.App.init({
     "appID":"111",

     "eventID":"500603196",// 高级功能-自定义事件统计ID，配置开通后在初始化处填写

     "statPullDownFresh":true, // 使用分析-下拉刷新次数/人数，必须先开通自定义事件，并配置了合法的eventID

     "statShareApp":true, // 使用分析-分享次数/人数，必须先开通自定义事件，并配置了合法的eventID

     "statReachBottom":true // 使用分析-页面触底次数/人数，必须先开通自定义事件，并配置了合法的eventID
    });
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || [];
    logs.unshift(Date.now());
    wx.setStorageSync('logs', logs);

      const updateManager = wx.getUpdateManager()

      updateManager.onCheckForUpdate(function (res) {
          // 请求完新版本信息的回调
          console.log(res.hasUpdate);
      });

      //有新版本强制更新
      updateManager.onUpdateReady(function () {
          wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                  if (res.confirm) {
                      // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                      updateManager.applyUpdate();
                  }else {
                      updateManager.applyUpdate();
                  }
              }
          })
      });

      updateManager.onUpdateFailed(function () {
          // 新的版本下载失败
          wx.showModal({
              title: '更新提示',
              content: '新版本下载失败',
              showCancel:false
          })
      });

  },
  /**
  *res :获取用户昵称、头像数据
  *cb:授权登录成功后回调函数
  *isUpdate:表示是否为更新资料
  */
  getUserInfo:function(res,cb,isUpdate){
    var that = this
      //调用登录接口
      wx.login({
        timeout:5000,
        success: function (resda) {
          //显示授权获取用户头像信息
          if(res) {
            var user = res.userInfo;
            user.code = resda.code;
            user.rawData = res.rawData;
            user.encryptedData = res.encryptedData;
            //更新资料流程
            if(isUpdate) {
              that.setUserOpenId(isUpdate,resda.code,user.nickName,user.avatarUrl,user,cb);
            } else{
                that.setUserOpenId(isUpdate,resda.code,user.nickName,user.avatarUrl,user,cb);
              // wx.showLoading({
              //   title:'定位中...'
              // });
              // wx.getLocation({
              //   success:function(data) {
              //     wx.hideLoading();
              //     var latitude = data.latitude;
              //     var longitude = data.longitude;
              //     that.setUserOpenId(isUpdate,resda.code,res.nickName,res.avatarUrl,res.encryptedData,res.rawData,cb,latitude,longitude);
              //   },
              //   fail: function(error) {
              //     wx.hideLoading();
              //     that.setUserOpenId(isUpdate,resda.code,res.nickName,res.avatarUrl,res.encryptedData,res.rawData,cb);
              //   }
              // });
            }

          } else {
            //隐性授权流程
            that.setUserOpenId(isUpdate,resda.code,null,null,null,null,cb);
          }
        },
        fail:function(error){
          logger.error('wx:login','微信登录授权接口失败,请检查您的网络!');
          wx.showToast({
            title:'微信登录授权接口失败,请检查您的网络!',
            icon:'none'
          });
        }
      })
  },
  setUserOpenId(isUpdate,code,nickName,avatarUrl,user,cb){
    var params = {};
    if(code) {
      params.code = code;
    }
    if(nickName) {
      params.nickName = nickName;
    }
    if(avatarUrl){
      params.avatarUrl = avatarUrl;
    }
    params.country = user.country;
    params.province = user.province;
    params.city = user.city;
    params.gender = user.gender;

    userService.login(params).then((data) => {
      if(!data.result) {
        wx.showToast({
          title: '登录失败' + data.msg,
          icon:'none'
        })
        wx.clearStorageSync('user');
        return;
      }
      var user = {};
      user.openid = data.obj;
      wx.setStorageSync('user', user);//存储openid
      typeof cb == "function" && cb(user)
      }, (error) => {
        wx.clearStorageSync('user');
    });
  },
  onShow: function() {
  },
  assets:assets,
  assetsByEnv:assetsByEnv,
  globalData:{
    //用户下单当前选择地址
    chooseAddrId:'',
    isPhoneX:false,
    Shop:{
        platform_show:null,
    },
    actnickNameity_id: null,
    mid: null,
    use_id: null,
    sn:null,
    work_sn:null,
    qrcode: null,
    //配置tabBar
    tabBar: {
      "color": "#9E9E9E",
      "selectedColor": "#f00",
      "backgroundColor": "#fff",
      "borderStyle": "#f5f5f5",
      "list": [
        {
          "pagePath": "/pages/shopIndex/shopIndex",
          "text": "首页",
          "iconPath": assets+"/home.png",
          "selectedIconPath": assets+"/home_sel.png",
          "selectedColor": "#ff2741",
          actnickNamee: false,
          type: 'url'
        },
        { "pagePath": "/pages/scanCode/scanCode",
          "text": "码上有礼",
          "iconPath": assets+"/saoma.png",
          "selectedIconPath": assets+"/saoma_sel.png",
          "selectedColor": "#ff2741",
          actnickNamee: false,
          type:'url'
        },
        {
          "pagePath": "/pages/messageList/messageList",
          "text": "消息",
          "iconPath": assets+"/msg.png",
          "selectedIconPath": assets+"/msg_sel.png",
          "selectedColor": "#ff2741",
          actnickNamee: false,
          type: 'message',
          messageNum: 0
        },
        {
          "pagePath": "/pages/index/index",
          "text": "我的",
          "iconPath": assets+"/me.png",
          "selectedIconPath": assets+"/me_sel.png",
          "selectedColor": "#ff2741",
          actnickNamee: false,
          type: 'yyfw',
          show_status:0
        }
      ],
      "position": "bottom"
    },
    indexActnickNamee: true, // tabbar激活状态
    msgActnickNamee: false // tabbar激活状态
  }
})
